﻿using DataAccess;
using DataEntity;
using IntelligentQuery.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Tools;

namespace WebUI.Controllers
{
    public class ListManageController : Controller
    {
        // 进货单录入
        // GET: /ListManage/
        private DataContext db = new DataContext();
        private Common tc = new Common();
        private IEntityRepository<OffPurchaseBill> PurchaseBillRepository;
        /// <summary>
        /// 入库单明细
        /// </summary>
        private IEntityRepository<OffPurchaseBillDetail> PurchaseBillDetailRepository;
       /// <summary>
       /// 系统计数表
       /// </summary>
        private IEntityRepository<SysConfig> ConfigRepository;
        public ListManageController()
        {
            PurchaseBillRepository = new EntityRepository<OffPurchaseBill>(db);
            ConfigRepository = new EntityRepository<SysConfig>(db);
            PurchaseBillDetailRepository = new EntityRepository<OffPurchaseBillDetail>(db);
        }
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Grid()
        {
            return PartialView();
        }
        #region  json返回数据
        /// <summary>
        /// 入库单json信息
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult PurchaseBillJson(int? page, int? rows, string model)
        {
            int Page = page ?? 1;
            int Rows = rows ?? 10;
            QueryModel QModel = null;
            Dictionary<string, object> JsonObj = new Dictionary<string, object>();
            if (!string.IsNullOrWhiteSpace(model))
            {
                QModel = IntelligentQuery.AjaxQueryConverter.ToQueryModel(model);
            }


            var purchaseBill = PurchaseBillRepository.Get(QModel).Where(n => !n.BeLock).ToList();

            JsonObj.Add("total", purchaseBill.Count());
            JsonObj.Add("rows", purchaseBill.OrderBy(n=>n.SortNumber)
                    .Skip((Page - 1) * Rows)
                   .Take(Rows).Select(s => new { s.ID, s.Bookkeeper,s.Code,s.Consignee,s.DeliveryCompany,s.OrderNumber,s.Name,s.SortNumber,s.SourceProperties,s.StorageTime, s.Remark, s.BeLock }));


            return JsonHelper.JsonEx(JsonObj);
        }

        #endregion
        #region 操作数据
        /// <summary>
        /// 新建/编辑页
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult CreateEdit(int id = 0)
        {
            var model = new OffPurchaseBill();
            model.StorageTime = System.DateTime.Now;
            model.SortNumber = 0;
            model.Code = tc.GetBillNumber(ConfigRepository.Get().FirstOrDefault().PurchaseBillID + 1);

            if (id != 0)
            {
                model = PurchaseBillRepository.GetByKey(id);
            }
            return PartialView(model);
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Save(OffPurchaseBill model)
        {
            try
            {

                if (model.ID == 0)
                {

                    PurchaseBillRepository.Insert(model);
                    var config = ConfigRepository.Get().FirstOrDefault();
                    config.PurchaseBillID = config.PurchaseBillID + 1;
                    ConfigRepository.Update(config);

                    
                }
                else
                {
                    OffPurchaseBill purchaseBill = PurchaseBillRepository.GetByKey(model.ID);

                    purchaseBill.Bookkeeper = model.Bookkeeper;
                    purchaseBill.Code = model.Code;
                    purchaseBill.Consignee = model.Consignee;
                    purchaseBill.DeliveryCompany = model.DeliveryCompany;
                    purchaseBill.Name = model.Name;
                    purchaseBill.OrderNumber = model.OrderNumber;
                    purchaseBill.SortNumber = model.SortNumber;
                    purchaseBill.SourceProperties = model.SourceProperties;
                    purchaseBill.StorageTime = model.StorageTime;
                    purchaseBill.Remark = model.Remark;
                    purchaseBill.IsBillStorage = model.IsBillStorage;
                    PurchaseBillRepository.Update(purchaseBill);

                }


                return Json(new { success = true });
            }
            catch (Exception e)
            {
                return Json(new { msg = e.Message });
            }
        }
        /// <summary>
        /// 单个删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult SingleDelete(int id)
        {
            try
            {
                var purchaseBill = PurchaseBillRepository.GetByKey(id);
                purchaseBill.BeLock = true;
                PurchaseBillRepository.Update(purchaseBill);

                return Json(new { success = true });
            }
            catch (Exception e)
            {
                return Json(new { msg = e.Message });
            }
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult BatchDelete(string ids)
        {
            try
            {
                List<string> list_id = ids.Split(',').ToList();
                var purchaseBillList = PurchaseBillRepository.Get().ToList().Where(u => list_id.Contains(u.ID.ToString())).ToList();
                foreach (var purchaseBill in purchaseBillList)
                {
                    purchaseBill.BeLock = true;

                }
                PurchaseBillRepository.Update(purchaseBillList);
                return Json(new { success = true });
            }
            catch (Exception e)
            {
                return Json(new { msg = e.Message });
            }
        }


        #endregion

        /// <summary>
        /// 打印入库单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult PrintPurchaseBill(int id)
        {
            var purchaseBillDetailList = PurchaseBillDetailRepository.Get(n => n.OffPurchaseBillID == id).OrderBy(n => n.AfterTaxPrice).ToList();
            ViewBag.PurchaseBill = PurchaseBillRepository.GetByKey(id);
            ViewBag.Count = 6-purchaseBillDetailList.Count();
            return PartialView(purchaseBillDetailList);
        }
    
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

    }
}
